package com.sws.orderMS.command.impl;

import java.util.ArrayList;
import java.util.List;

import com.sws.orderMS.OrderMSDao;
import com.sws.orderMS.command.UserCommand;
import com.sws.orderMS.pojo.Client;
import com.sws.orderMS.pojo.Order;
import com.sws.orderMS.pojo.OrderItem;
import com.sws.orderMS.pojo.User;
import com.sws.orderMS.tool.Tool;

public class PayCommand extends UserCommand {

	public PayCommand(User userProfile) {
		super(userProfile);
	}

	@Override
	public void execute() {
		Client client = (Client)userProfile;
		OrderMSDao dao = new OrderMSDao();
		List<Order> orders = new ArrayList<>();
		List<Order> tempList = dao.searchAllOrders(client);
		for (Order order: tempList) {
			if (order.getCurrentStatus() != 4) {
				orders.add(order);
			}
		}
		if (orders.isEmpty()) {
			Tool.printMsg("暂无待支付的订单");
			return;
		}
		showOrders(orders);
		String orderNo = Tool.askUserInputNotNull("请输入需要付款的订单号:");
		Order order2pay = null;
		for (Order order: orders) {
			if (order.getOrderNo().equals(orderNo)) {
				order2pay = order;
			}
		}
		if (order2pay == null) {
			Tool.printMsg("Invalid input!");
			return;
		}
		Tool.printMsg("合计:" + order2pay.getTotal() + "元");
		double total = order2pay.getTotal();
		double own = client.getWallet().getBalance();
		String payType = Tool.askUserInputNotNull("请选择付款方式 (Alipay|Wechat|Unionpay):");
		client.getWallet().initMap();
		order2pay.setPaymentMethodId(client.getWallet().getPaymentMethodId(payType));
		String toPay = Tool.askUserInputNotNull("确认支付？Y|N");
		if ("Y".equalsIgnoreCase(toPay)) {
			if (total > own) {
				order2pay.setCurrentPaymentStatus(3);
				Tool.printMsg("抱歉, 您的账户余额不足！请先进行充值");
				dao.updatePayment(order2pay);
				return;
			}
			order2pay.setCurrentPaymentStatus(2);
			dao.updatePayment(order2pay);
			dao.updateInventory(order2pay);
			dao.updateUserBalance(own - total, client.getId());
			client.getWallet().setBalance(own - total);
			dao.updateOrderStatuss(4, order2pay);
			Tool.printMsg("支付成功!");
		}
	}

	private void showOrders(List<Order> orders) {
		for (Order order: orders) {
			String status = order.getOrderStatus(order.getCurrentStatus());
			if (order.getCurrentStatus() != 4) {
				status = order.getPaymentStatus(order.getCurrentPaymentStatus());
			}
			Tool.printMsg("订单号:" + order.getOrderNo() + 
					", 订单状态:" + status);
			for (OrderItem item: order.getOrderList()) {
				Tool.printMsg(item.getProduct().getName() + "\t\t" + "x" + item.getAmount());
			}
			
			int num = 0;
			for (OrderItem item: order.getOrderList()) {
				num = num + item.getAmount();
			}
		
			double pay = 0;
			if (order.getCurrentStatus() == 4) {
				pay = order.getTotal();
			}
			String total = pay == 0 ? "" : ", 实付" + pay + "元";
			Tool.printMsg("共" + num + "件商品" + total);
			
		}
	
	}
	
}
